package org.fireking.myapplication

import android.app.ProgressDialog
import android.graphics.Color
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.listener.OnChartGestureListener
import android.view.MotionEvent
import android.widget.Toast
import com.github.mikephil.charting.listener.ChartTouchListener
import java.util.*
import kotlin.concurrent.thread
import kotlin.math.ceil
import kotlin.math.floor

class MainActivity : AppCompatActivity(), OnChartGestureListener {

    private lateinit var lineChart: LineChart
    private lateinit var chartColors: IntArray
    private lateinit var progressDialog: ProgressDialog
    private lateinit var tvRangeInfo: TextView
    private lateinit var drawingView: ChartDrawingInteractionView

    // 绘图管理器
    private lateinit var drawingManager: ChartDrawingManager

    // 绘图工具按钮
    private lateinit var btnNone: Button
    private lateinit var btnLine: Button
    private lateinit var btnRectangle: Button
    private lateinit var btnCurve: Button
    private lateinit var btnEdit: Button
    private lateinit var btnMoveToFront: Button
    private lateinit var btnMoveToBack: Button
    private lateinit var btnUndo: Button
    private lateinit var btnClear: Button

    // 当前选中的按钮
    private var currentSelectedButton: Button? = null

    // 绘图工具颜色
    private val colorToolSelected by lazy { resources.getColor(R.color.drawingToolSelected, null) }
    private val colorToolNormal by lazy { resources.getColor(R.color.drawingToolNormal, null) }
    private val colorToolText by lazy { resources.getColor(R.color.drawingToolText, null) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)

        // 初始化颜色数组
        initChartColors()

        // 初始化视图
        tvRangeInfo = findViewById(R.id.tvRangeInfo)
        drawingView = findViewById(R.id.drawingView)

        // 设置状态栏边距
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 初始化图表
        setupChart()

        // 初始化绘图工具
        setupDrawingTools()

        // 初始化进度对话框
        setupProgressDialog()

        // 生成数据并展示 - 改为3条线
        loadChartDataInBackground()
    }

    private fun setupProgressDialog() {
        progressDialog = ProgressDialog(this).apply {
            setTitle("加载图表")
            setMessage("正在生成3条线条数据，每条1000个点...")
            setCancelable(false)
            setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
            max = 100
            progress = 0
        }
    }

    private fun initChartColors() {
        chartColors = intArrayOf(
            resources.getColor(R.color.colorChart1, null),
            resources.getColor(R.color.colorChart2, null),
            resources.getColor(R.color.colorChart3, null),
            resources.getColor(R.color.colorChart4, null),
            resources.getColor(R.color.colorChart5, null),
            resources.getColor(R.color.colorChart6, null),
            resources.getColor(R.color.colorChart7, null),
            resources.getColor(R.color.colorChart8, null),
            resources.getColor(R.color.colorChart9, null),
            resources.getColor(R.color.colorChart10, null),
            resources.getColor(R.color.colorChart11, null),
            resources.getColor(R.color.colorChart12, null)
        )
    }

    private fun setupChart() {
        lineChart = findViewById(R.id.lineChart)

        // 初始化绘图管理器
        drawingManager = ChartDrawingManager(lineChart)

        // 将绘图交互视图关联到绘图管理器
        drawingView.attachToDrawingManager(drawingManager)

        // 启用交互功能
        lineChart.apply {
            // 设置手势监听器
            onChartGestureListener = this@MainActivity

            // 启用拖动
            isDragEnabled = true

            // 启用缩放
            isScaleXEnabled = true
            isScaleYEnabled = true

            // 启用双指缩放
            setPinchZoom(true)

            // 关闭描述文本
            description.isEnabled = false

            // 设置图例位置和样式
            legend.apply {
                form = Legend.LegendForm.LINE
                textSize = 11f
                verticalAlignment = Legend.LegendVerticalAlignment.BOTTOM
                horizontalAlignment = Legend.LegendHorizontalAlignment.CENTER
                orientation = Legend.LegendOrientation.HORIZONTAL
                setDrawInside(false)
                isEnabled = true  // 启用图例，因为只有3条线
            }

            // 设置X轴
            xAxis.apply {
                position = XAxis.XAxisPosition.BOTTOM
                textSize = 10f
                setDrawGridLines(true)
                granularity = 10f  // 修改为每10个点显示一个标签，更适合50个点的视图
            }

            // 设置左Y轴
            axisLeft.apply {
                textSize = 10f
                setDrawGridLines(true)
            }

            // 禁用右Y轴
            axisRight.isEnabled = false

            // 其他设置
            isAutoScaleMinMaxEnabled = true

            // 设置默认可见点范围为50点
            setVisibleXRangeMaximum(50f)

            // 设置背景颜色
            setBackgroundColor(Color.WHITE)

            // 设置更宽的边距，使图表不要太贴近边缘
            setExtraOffsets(10f, 10f, 10f, 10f)
        }
    }

    private fun setupDrawingTools() {
        // 初始化按钮
        btnNone = findViewById(R.id.btnNone)
        btnLine = findViewById(R.id.btnLine)
        btnRectangle = findViewById(R.id.btnRectangle)
        btnCurve = findViewById(R.id.btnCurve)
        btnEdit = findViewById(R.id.btnEdit)
        btnMoveToFront = findViewById(R.id.btnMoveToFront)
        btnMoveToBack = findViewById(R.id.btnMoveToBack)
        btnUndo = findViewById(R.id.btnUndo)
        btnClear = findViewById(R.id.btnClear)

        // 初始化按钮颜色
        setButtonsStyle()

        // 默认选中"图表浏览"按钮
        selectDrawingButton(btnNone)

        // 设置按钮点击事件
        btnNone.setOnClickListener {
            selectDrawingButton(it as Button)
            drawingManager.drawingMode = ChartDrawingManager.DrawingMode.NONE
        }

        btnLine.setOnClickListener {
            selectDrawingButton(it as Button)
            drawingManager.drawingMode = ChartDrawingManager.DrawingMode.LINE
        }

        btnRectangle.setOnClickListener {
            selectDrawingButton(it as Button)
            drawingManager.drawingMode = ChartDrawingManager.DrawingMode.RECTANGLE
        }

        btnCurve.setOnClickListener {
            selectDrawingButton(it as Button)
            drawingManager.drawingMode = ChartDrawingManager.DrawingMode.CURVE
        }

        btnEdit.setOnClickListener {
            selectDrawingButton(it as Button)
            drawingManager.drawingMode = ChartDrawingManager.DrawingMode.EDIT
        }

        btnMoveToFront.setOnClickListener {
            drawingManager.bringSelectedShapeToFront()
        }

        btnMoveToBack.setOnClickListener {
            drawingManager.sendSelectedShapeToBack()
        }

        btnUndo.setOnClickListener {
            drawingManager.undo()
        }

        btnClear.setOnClickListener {
            drawingManager.clearDrawings()
        }
    }

    private fun setButtonsStyle() {
        // 设置所有按钮为默认样式
        val buttons = listOf(
            btnNone,
            btnLine,
            btnRectangle,
            btnCurve,
            btnEdit,
            btnMoveToFront,
            btnMoveToBack,
            btnUndo,
            btnClear
        )
        for (button in buttons) {
            button.setBackgroundColor(colorToolNormal)
            button.setTextColor(colorToolText)
        }

        // 为图层操作按钮设置特殊颜色
        val layerButtons = listOf(btnMoveToFront, btnMoveToBack)
        for (button in layerButtons) {
            button.setBackgroundColor(resources.getColor(R.color.colorAccent, null))
            button.setTextColor(Color.WHITE)
        }
    }

    private fun selectDrawingButton(button: Button) {
        // 如果有当前选中的按钮，恢复其默认样式
        currentSelectedButton?.let {
            it.setBackgroundColor(colorToolNormal)
            it.setTextColor(colorToolText)
        }

        // 将新按钮设为选中状态
        button.setBackgroundColor(colorToolSelected)
        button.setTextColor(Color.WHITE)

        // 更新当前选中按钮引用
        currentSelectedButton = button
    }

    private fun loadChartDataInBackground(lineCount: Int = 1) {
        progressDialog.show()

        thread {
            val dataSets = generateData(lineCount)

            // 在UI线程设置数据
            runOnUiThread {
                // 最终更新
                lineChart.data = LineData(dataSets)

                // 使图表移动到开始位置
                lineChart.moveViewToX(0f)

                // 设置可见范围为前50个点
                lineChart.setVisibleXRange(0f, 50f)

                // 更新范围信息
                updateRangeInfo()

                // 刷新
                lineChart.invalidate()

                // 关闭对话框
                progressDialog.dismiss()
            }
        }
    }

    private fun generateData(lineCount: Int): List<LineDataSet> {
        val random = Random()
        val dataSets = ArrayList<LineDataSet>()

        // 修改为生成指定数量的线条（3条）
        for (i in 0 until lineCount) {
            val entries = ArrayList<Entry>()

            // 为每条线生成1000个点
            for (j in 0 until 1000) {
                // 不同的线使用不同的函数生成Y值，使它们更容易区分
                val y = when (i) {
                    0 -> random.nextFloat() * 50 + 25 + (Math.sin(j / 100.0) * 20).toFloat()  // 正弦波形
                    1 -> random.nextFloat() * 30 + 50 + (j / 30.0).toFloat()  // 上升趋势
                    else -> random.nextFloat() * 60 + (Math.cos(j / 80.0) * 30).toFloat()  // 余弦波形
                }
                entries.add(Entry(j.toFloat(), y))
            }

            // 创建数据集
            val lineName = when (i) {
                0 -> "正弦波线"
                1 -> "上升趋势线"
                else -> "余弦波线"
            }
            val dataSet = LineDataSet(entries, lineName)
            dataSet.apply {
                // 使用资源文件中定义的颜色
                color = chartColors[i % chartColors.size]
                setDrawCircles(false)  // 不绘制圆点，提高性能
                lineWidth = 2f  // 线条加粗，更容易看清
                mode = LineDataSet.Mode.LINEAR
                setDrawValues(false)  // 不绘制数值，提高性能

                // 由于只有3条线，可以启用高亮功能
                isHighlightEnabled = true
                highLightColor = Color.BLACK

                // 禁用填充
                setDrawFilled(false)
            }

            dataSets.add(dataSet)

            // 更新进度
            val progress = ((i + 1) * 100 / lineCount)
            runOnUiThread {
                progressDialog.progress = progress
                progressDialog.setMessage("正在生成数据... $progress%")
            }
        }

        return dataSets
    }

    // 更新显示范围信息
    private fun updateRangeInfo() {
        val lowestX = floor(lineChart.lowestVisibleX).toInt()
        val highestX = ceil(lineChart.highestVisibleX).toInt()
        tvRangeInfo.text = "可见范围: $lowestX-$highestX 点 (共${highestX - lowestX}点)"
    }

    // 图表手势监听器接口实现
    override fun onChartGestureStart(
        me: MotionEvent?,
        lastPerformedGesture: ChartTouchListener.ChartGesture?
    ) {
    }

    override fun onChartGestureEnd(
        me: MotionEvent?,
        lastPerformedGesture: ChartTouchListener.ChartGesture?
    ) {
        updateRangeInfo()
    }

    override fun onChartLongPressed(me: MotionEvent?) {}

    override fun onChartDoubleTapped(me: MotionEvent?) {}

    override fun onChartSingleTapped(me: MotionEvent?) {}

    override fun onChartFling(
        me1: MotionEvent?,
        me2: MotionEvent?,
        velocityX: Float,
        velocityY: Float
    ) {
        // 图表飞滑时更新范围信息
        updateRangeInfo()
    }

    override fun onChartScale(me: MotionEvent?, scaleX: Float, scaleY: Float) {
        updateRangeInfo()
    }

    override fun onChartTranslate(me: MotionEvent?, dX: Float, dY: Float) {
        updateRangeInfo()
    }
}